package wang.jinggo.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 * @description 获取客户端ip
 * @author yusx
 * @date 2017年8月31日 下午3:30:27
 */
public class IPUtil {

	private static final Logger LOG = LoggerFactory.getLogger(IPUtil.class);

	public static String getIpAddress(HttpServletRequest request) {
		String ip = request.getHeader("X-Real-IP");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("x-forwarded-for");
			LOG.info("x-forwarded-for:" + ip);
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
			LOG.info("Proxy-Client-IP:" + ip);
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
			LOG.info("WL-Proxy-Client-IP:" + ip);
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
			LOG.info("getRemoteAddr:" + ip);
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("http_client_ip");
			LOG.info("http_client_ip:" + ip);
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("HTTP_X_FORWARDED_FOR");
			LOG.info("HTTP_X_FORWARDED_FOR:" + ip);
		}
		if (ip != null && ip.indexOf(",") != -1) {
			ip = ip.substring(ip.lastIndexOf(",") + 1, ip.length()).trim();
		}
		if ("0:0:0:0:0:0:0:1".equals(ip)) {
			ip = "127.0.0.1";
		}
		LOG.info("FINAL_IP:" + ip);
		return ip;
	}
	
	//获取服务器IP
    public static String getServerIp(){ 
    	InetAddress addr = null;     
        try {  
            addr = InetAddress.getLocalHost();  
        } catch (UnknownHostException e) {   
            return "unkownhost";
        }     
      
	    byte[] ipAddr = addr.getAddress();     
	    String ipAddrStr = "";     
	    for (int i = 0; i < ipAddr.length; i++) {     
	        if (i > 0) {     
	            ipAddrStr += ".";     
	        }     
	        ipAddrStr += ipAddr[i] & 0xFF;     
	    }         
        return ipAddrStr;   
       }
    
    //判断是否内网Ip
    public static boolean isInner(String ip)
    {
        String reg = "(10|172|192)\\.([0-1][0-9]{0,2}|[2][0-5]{0,2}|[3-9][0-9]{0,1})\\.([0-1][0-9]{0,2}|[2][0-5]{0,2}|[3-9][0-9]{0,1})\\.([0-1][0-9]{0,2}|[2][0-5]{0,2}|[3-9][0-9]{0,1})";
        Pattern p = Pattern.compile(reg);
        Matcher matcher = p.matcher(ip);
        return matcher.find();
    }
    
    
    public static void main(String[] args) 
	{
		System.out.println(isInner("null"));
	}
}

